package com.sgb.kjwl.view.ui.adapter.home;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.text.Html;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.databinding.DataBindingUtil;
import androidx.databinding.ViewDataBinding;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.chad.library.adapter.base.BaseMultiItemQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.makeramen.roundedimageview.RoundedImageView;
import com.sgb.kjwl.BR;
import com.sgb.kjwl.R;
import com.sgb.knowledgeshare.utils.SharePermissionUtils;
import com.swgk.core.util.UserOperating;
import com.sgb.kjwl.view.ui.activity.self.logistics.QuotedOwnerActivity;
import com.sgb.kjwl.view.ui.activity.self.logistics.QuotedThirdActivity;
import com.sgb.link.utils.LogisticsLogUtils;
import com.swgk.core.base.model.entity.VideoBean;
import com.sgb.kjwl.model.entity.transport.GoodsInfoEntity;
import com.sgb.kjwl.model.entity.transport.SingleItemConstant;
import com.sgb.kjwl.utils.CargoConstant;
import com.sgb.kjwl.utils.NumberUtil;
import com.sgb.kjwl.utils.VehicleConstant;
import com.sgb.knowledgeshare.view.activity.HomeShareActivity;
import com.sgb.kjwl.view.ui.activity.self.userInfo.VerificationCodeLoginActivity;
import com.sgb.knowledgeshare.view.activity.PlayListActivity;
import com.sgb.kjwl.view.ui.adapter.transport.GoodsInfoVideoAdapter;
import com.sgb.kjwl.view.widget.CenteredImageSpan;
import com.swgk.core.dialog.RoundCornerDialog;
import com.swgk.core.recyclerview.adapter.AdapterOnItemClick;
import com.swgk.core.util.MToast;
import com.swgk.core.util.SharedPreferenceUtil;
import com.swgk.core.util.StringUtil;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

public class GoodsInfoAdapter extends BaseMultiItemQuickAdapter<GoodsInfoEntity, BaseViewHolder> {

    private static final String TAG = "GoodsInfoAdapter";
    private static final int MIN_CLICK_DELAY_TIME = 2000;
    private static long lastClickTime;
    private boolean isSelf = false;
    public String pageName;//埋点路径名称1-普通货源列表  2-竞价货源列表页 7-首页-找货源列表   8-首页-竞价货运列表

    public void setPageName(String pageName) {
        this.pageName = pageName;
    }

    public GoodsInfoAdapter(Context context, List<GoodsInfoEntity> datas) {
        super(datas);
        mContext = context;
        addItemType(SingleItemConstant.TYPE_ONE, R.layout.item_goods_info);
        addItemType(SingleItemConstant.TYPE_TWO, R.layout.item_list);
    }

    public GoodsInfoAdapter(Context context, List<GoodsInfoEntity> datas, boolean isSelf) {
        super(datas);
        mContext = context;
        addItemType(SingleItemConstant.TYPE_ONE, R.layout.item_goods_info);
        addItemType(SingleItemConstant.TYPE_TWO, R.layout.item_list);
        this.isSelf = isSelf;
    }


    @Override
    public void convert(BaseViewHolder holder, GoodsInfoEntity goodsInfoEntity) {
        switch (goodsInfoEntity.getItemType()) {
            case SingleItemConstant.TYPE_ONE:
                bindGoodsInfo(holder, goodsInfoEntity);
                break;
            case SingleItemConstant.TYPE_TWO:
                bindVideoInfo(holder, goodsInfoEntity);
                break;
        }
    }

    @Override
    public void setOnItemChildClickListener(OnItemChildClickListener listener) {
        super.setOnItemChildClickListener(listener);
    }

    private void bindGoodsInfo(BaseViewHolder holder, GoodsInfoEntity goodsInfoEntity) {

        ViewDataBinding binding = DataBindingUtil.bind(holder.itemView);
        binding.setVariable(BR.viewModel, goodsInfoEntity);
        binding.executePendingBindings();

        //前台主页 物流需求--自己发布的货源不需要展示发布者身份信息
        RelativeLayout identity_info = holder.getView(R.id.identity_info);
        if (isSelf) {
            identity_info.setVisibility(View.GONE);
        } else {
            identity_info.setVisibility(View.VISIBLE);
        }

        TextView type_name = holder.getView(R.id.type_name);
        TextView price_view = holder.getView(R.id.price_view);
        TextView content_view = holder.getView(R.id.content_view);
        TextView tv_company = holder.getView(R.id.tv_company);
        TextView role = holder.getView(R.id.role);
        TextView tv_distance = holder.getView(R.id.tv_distance);
        TextView tv_city = holder.getView(R.id.tv_city);
        TextView tv_lowest_price = holder.getView(R.id.tv_lowest_price);
        TextView car_number = holder.getView(R.id.car_number);
        TextView tvjourney = holder.getView(R.id.transport_distance);
        TextView load_time = holder.getView(R.id.load_time);
        RoundedImageView iv_logo = holder.getView(R.id.iv_logo);
        ImageView loadType = holder.itemView.findViewById(R.id.load_type);

        String wightStr = (TextUtils.isEmpty(goodsInfoEntity.getWeight()) || TextUtils.isDigitsOnly(goodsInfoEntity.getWeight()) ? "" : "/" + NumberUtil.trim0(goodsInfoEntity.getWeight()) + "吨");
        String volumeStr = TextUtils.isEmpty(goodsInfoEntity.getVolume()) ? "" : "/" + NumberUtil.trim0(goodsInfoEntity.getVolume()) + "方";
        type_name.setText(goodsInfoEntity.getGoodsLastTypeName() + wightStr + volumeStr);
        String carModelNameStr = TextUtils.isEmpty(goodsInfoEntity.getCarModelName()) ? "" : goodsInfoEntity.getCarModelName();
        String carLenStr = TextUtils.isEmpty(goodsInfoEntity.getCarLenName()) ? "" : " " + goodsInfoEntity.getCarLenName();
        String heightHurdleStr = getValidHeightHurdle(goodsInfoEntity.getHeightHurdle());
        String dumpStr = TextUtils.isEmpty(VehicleConstant.getIsDumpStr(goodsInfoEntity.getIsDump())) ? "" : " " + VehicleConstant.getIsDumpStr(goodsInfoEntity.getIsDump());
       /* if (goodsInfoEntity.getPattern() == 1) {
            content_view.setText(TextUtils.isEmpty(goodsInfoEntity.getOfferType()) ? "" : goodsInfoEntity.getOfferTypeWorlds() + " 可报价");
        } else {*/
            content_view.setText(carModelNameStr + carLenStr + heightHurdleStr + dumpStr);
      /*  }*/
       /* if (goodsInfoEntity.getPattern() == 0) {*/
            //整车/零担
            String loadTypeStr = CargoConstant.getTransportTypeStr(goodsInfoEntity.getTransportType());
            if (loadTypeStr.equals("零担")) {
                loadType.setVisibility(View.VISIBLE);
                loadType.setImageResource(R.drawable.icon_less_than_tag);
            } else if (loadTypeStr.equals("整车")) {
                loadType.setVisibility(View.VISIBLE);
                loadType.setImageResource(R.drawable.icon_carload_tag);
            } else {
                loadType.setVisibility(View.GONE);
            }
            //装货时间调整
            String loadTime = CargoConstant.stampFormatListLoadTime(
                    goodsInfoEntity.getShipmentTime(), goodsInfoEntity.getStartPointTime(),
                    goodsInfoEntity.getShipmentEndTime(), goodsInfoEntity.getEndPointTime());
            if (!TextUtils.isEmpty(loadTime)) {
                load_time.setText(loadTime + "装货");
            } else {
                load_time.setVisibility(View.GONE);
            }
       /* } else {
            loadType.setVisibility(View.GONE);
            //装货时间调整
            String loadTime = CargoConstant.stampFormatListLoadTime(
                    goodsInfoEntity.getShipmentTime(), goodsInfoEntity.getStartPointTime(),
                    goodsInfoEntity.getShipmentEndTime(), goodsInfoEntity.getEndPointTime());
            if (!TextUtils.isEmpty(loadTime)) {
                load_time.setText(loadTime + " 装货");
            } else {
                load_time.setVisibility(View.GONE);
            }
        }*/

        // 一口价/电议
        if (goodsInfoEntity.getFreightType() == 1) {
            price_view.setText("运费合计 电议");
        } else {
            price_view.setText(!goodsInfoEntity.getAllFreight().isEmpty() ? mContext.getResources().getString(R.string.app_the_freight_combined)+" " + NumberUtil.trim0(goodsInfoEntity.getAllFreight()) + "元" : "");
        }

        tv_company.setText(goodsInfoEntity.getCompanyName());
        if (TextUtils.isEmpty(goodsInfoEntity.getJourney())) {
            tvjourney.setText("");
            tvjourney.setVisibility(View.GONE);
        } else {
            tvjourney.setVisibility(View.VISIBLE);
            String journey = Double.valueOf(goodsInfoEntity.getJourney()) < 1000 ? "1km以内" : StringUtil.fromatUpDistance(goodsInfoEntity.getJourney()) + "km";
            tvjourney.setText("运程 " + journey);
        }

        if (TextUtils.isEmpty(goodsInfoEntity.getDistance())) {
            tv_distance.setText("");
        } else {
            tv_distance.setText("距您 " + (Double.valueOf(goodsInfoEntity.getDistance()) < 1000 ? "1km以内" : StringUtil.fromatUpDistance(goodsInfoEntity.getDistance()) + "km"));
        }

        if (goodsInfoEntity.getPattern() == 1) {
            Drawable drawable = mContext.getResources().getDrawable(R.drawable.icon_jingjia);
            drawable.setBounds(0, 0, drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight());
            CenteredImageSpan imgSpan = new CenteredImageSpan(drawable);
            SpannableString spannableString = new SpannableString(goodsInfoEntity.getCityName() + " " + goodsInfoEntity.getDistrictName() + " ➞ " + goodsInfoEntity.getDestCityName() + " " + goodsInfoEntity.getDestDistrictName() + "   ");
            spannableString.setSpan(imgSpan, spannableString.length() - 1, spannableString.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
            tv_city.setText(spannableString);
          /*  if (!TextUtils.isEmpty(goodsInfoEntity.getLowestPrice())) {
                tv_lowest_price.setVisibility(View.VISIBLE);
                tv_lowest_price.setText(Html.fromHtml("<font>最低报价 </font>" + "<font color='#000000'>" + NumberUtil.trim0(goodsInfoEntity.getLowestPrice()) + "元/吨" + "</font>"));
                if (goodsInfoEntity.getCarNumber() > 0) {
                    car_number.setText(Html.fromHtml("意向人数 " + "<font color='#5792FD'>" + goodsInfoEntity.getCarNumber() + ">>" + "</font>"));
                    car_number.setVisibility(View.VISIBLE);
                } else {
                    car_number.setVisibility(View.GONE);
                }
            } else {
                tv_lowest_price.setVisibility(View.GONE);
                car_number.setVisibility(View.GONE);
            }*/
        } else {
            tv_city.setText(goodsInfoEntity.getCityName() + " " + goodsInfoEntity.getDistrictName() + " ➞ " + goodsInfoEntity.getDestCityName() + " " + goodsInfoEntity.getDestDistrictName());
        }
        car_number.setOnClickListener(v -> {
            if (TextUtils.isEmpty(SharedPreferenceUtil.getInstance().
                    getSaveStringData(SharedPreferenceUtil.LOGIN_TOKEN, ""))) {
                VerificationCodeLoginActivity.start(mContext);
            } else {
                if (UserOperating.getInstance().isCompany() && UserOperating.getInstance().getTeamOrCompanyNameNo().equals(goodsInfoEntity.getCompanyNo()) && goodsInfoEntity.getTerminal().equals("1")) {
                    //当前是企业并且跟货源发布人一致
                    QuotedOwnerActivity.start(mContext, goodsInfoEntity.getNo());
                } else if (UserOperating.getInstance().isTeam() && UserOperating.getInstance().getTeamOrCompanyNameNo().equals(goodsInfoEntity.getTeamNo()) && goodsInfoEntity.getTerminal().equals("2")) {
                    //当前是团队并且跟货源发布人一致
                    QuotedOwnerActivity.start(mContext, goodsInfoEntity.getNo());
                } else if (UserOperating.getInstance().isPersonal() && UserOperating.getInstance().getUserNo().equals(goodsInfoEntity.getUserNo()) && goodsInfoEntity.getTerminal().equals("3")) {
                    //当前是个人并且跟货源发布人一致
                    QuotedOwnerActivity.start(mContext, goodsInfoEntity.getNo());
                } else {
                    QuotedThirdActivity.start(mContext, goodsInfoEntity.getNo());
                }
            }
        });


        holder.getView(R.id.call_phone).setOnClickListener(v -> callPhone(goodsInfoEntity));
        if (!TextUtils.isEmpty(goodsInfoEntity.getTerminal())) {
            role.setVisibility(View.VISIBLE);
            if (!TextUtils.isEmpty(goodsInfoEntity.getCompanyName()))
                tv_company.setText(goodsInfoEntity.getCompanyName());
            switch (goodsInfoEntity.getTerminal()) {
                case "1":
                    role.setVisibility(View.VISIBLE);
                    role.setBackgroundResource(R.drawable.bg_blue_solid_ring);
                    role.setTextColor(Color.parseColor("#5792FD"));
                    role.setText("企业");
                    iv_logo.setOval(false);
                    iv_logo.setCornerRadius(4);
                    break;
                case "2":
                    //个人不展示
                case "3":
                    role.setVisibility(View.GONE);
                    iv_logo.setOval(true);
                    break;
            }
        }
    }

    private void bindVideoInfo(BaseViewHolder holder, GoodsInfoEntity goodsInfoEntity) {
        List<VideoBean> videoBeanList = new ArrayList<>();
        videoBeanList.addAll(goodsInfoEntity.getVideoList());
        if (videoBeanList.size() >= 6) {
            VideoBean v = new VideoBean();
            v.setType("查看更多视频");
            videoBeanList.add(v);
        }
        RecyclerView recyclerView = holder.getView(R.id.list_data);
        if (goodsInfoEntity.getVideoList() == null || goodsInfoEntity.getVideoList().size() == 0) {
            recyclerView.setVisibility(View.GONE);
            return;
        }
        recyclerView.setVisibility(View.VISIBLE);
        if (recyclerView.getAdapter() == null) {
            recyclerView.setLayoutManager(new LinearLayoutManager(mContext, LinearLayoutManager.HORIZONTAL, false));
            GoodsInfoVideoAdapter adapter = new GoodsInfoVideoAdapter(mContext, videoBeanList);
            adapter.setOnItemClick(new AdapterOnItemClick<VideoBean>() {
                @Override
                public void onItemClick(VideoBean homeHostVideoEntity, int position) {
                    if (homeHostVideoEntity.isCheckMoreVideos()) {
                        SharePermissionUtils.getPermissionTwo((Activity) mContext,1);
                    } else {
                        Intent intent = new Intent(mContext, PlayListActivity.class);
                        intent.putExtra(PlayListActivity.VIDEOLISTBEAN, (Serializable) adapter.getDatas());
                        intent.putExtra(PlayListActivity.PSO, position);
                        intent.putExtra(PlayListActivity.VIDEOTYPE, "goods_and_car_video");
                        mContext.startActivity(intent);
                    }
                }
            });
            recyclerView.setAdapter(adapter);
        } else {
            ((GoodsInfoVideoAdapter) recyclerView.getAdapter()).setDatas(videoBeanList);
        }
    }

    private void callPhone(GoodsInfoEntity goodsInfoEntity) {
        if (!isLogin()) {
            VerificationCodeLoginActivity.start(mContext);
            return;
        }
        if (!TextUtils.isEmpty(goodsInfoEntity.getConnectionPhone()))
            showDialog(goodsInfoEntity);
        else
            MToast.showLongToast(mContext, "无联系方式");
    }

    private String getValidHeightHurdle(String heightHurdle) {
        if (TextUtils.isEmpty(heightHurdle) || heightHurdle.equals("0.0")) {
            return "";
        }
        return " 栏高 " + NumberUtil.trim0(heightHurdle) + "米";
    }

    private boolean isLogin() {
        return !TextUtils.isEmpty(SharedPreferenceUtil.getInstance().
                getSaveStringData(SharedPreferenceUtil.LOGIN_TOKEN, ""));
    }


    private void showDialog(GoodsInfoEntity goodsInfoEntity) {
        View view = View.inflate(mContext, R.layout.dialog_two_btn, null);
        final RoundCornerDialog roundCornerDialog = new RoundCornerDialog(mContext, 0, 0, view, R.style.RoundCornerDialog);
        roundCornerDialog.show();
        roundCornerDialog.setCanceledOnTouchOutside(false);// 设置点击屏幕Dialog不消失
        //roundCornerDialog.setOnKeyListener(keylistener);//设置点击返回键Dialog不消失

        TextView tv_message = view.findViewById(R.id.tv_message);
        TextView tv_title = view.findViewById(R.id.tv_title);
        TextView tv_logout_confirm = view.findViewById(R.id.tv_logout_confirm);
        TextView tv_logout_cancel = view.findViewById(R.id.tv_logout_cancel);
        tv_title.setText("确认呼叫");
        tv_title.setVisibility(View.VISIBLE);
        tv_message.setText(goodsInfoEntity.getConnectionPhone());
        tv_logout_confirm.setText("拨打");
        //确定
        tv_logout_confirm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                LogisticsLogUtils.getInstance().logisticsFlow(pageName, "货源联系人", "icon");
                Intent intent = new Intent(Intent.ACTION_DIAL);
                Uri data = Uri.parse("tel:" + goodsInfoEntity.getConnectionPhone());
                intent.setData(data);
                mContext.startActivity(intent);
                roundCornerDialog.dismiss();

            }
        });
        //取消
        tv_logout_cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                roundCornerDialog.dismiss();
            }
        });
    }

    public void setDatas(List<GoodsInfoEntity> list) {
        if (list == null) {
            this.mData.clear();
        } else {
            this.mData = list;
        }
        notifyDataSetChanged();


    }

    public void setDataUnNotify(List<GoodsInfoEntity> list) {
        mData = list;
    }


    public boolean isMultipleClick() {
        long curClickTime = System.currentTimeMillis();
        if ((curClickTime - lastClickTime) >= MIN_CLICK_DELAY_TIME) {
            lastClickTime = curClickTime;
            return false;
        }
        return true;
    }

}
